# -*- coding: utf-8 -*-
from wbhttp import HttpClient
from logger import logger
from weibo import Weibo
import re


class WeiboGroup(Weibo):
    def get_all_groups(self):
        url = 'https://m.weibo.cn/msg/index?format=cards'
        resp = HttpClient.get(url)
        groups = []
        if resp.status_code == 200:
            for data in resp.json():
                if data['mod_type'] == 'mod/pagelist':
                    members = data['card_group']
                    for member in members:
                        if member['scheme'].startswith('/groupChat/userChat/chat'):
                            groups.append(member['user']['id'])
                    logger.info('获取群聊%d个' % len(groups))
        else:
            logger.info('获取群聊失败')
        return groups

    def send_to_group(self, groupId, text):

        headers = {
            'Referer': 'https://m.weibo.cn/',
            'Upgrade-Insecure-Requests': '1'
        }
        referUrl = 'https://m.weibo.cn/groupChat/userChat/chat?group_id=' + str(groupId)
        resp = HttpClient.get(referUrl, headers=headers)
        st = re.findall(r',"st":"(.*?)"', resp.text)[0]
        url = 'https://m.weibo.cn/groupChat/userChat/sendMsg'
        data = {
            'content': text,
            'group_id': str(groupId),
            'st': st,
        }

        headers = {
            'Referer': referUrl,
            'Origin': 'https://m.weibo.cn/'
        }
        resp = HttpClient.post(url, data, headers)
        if resp.status_code == 200 and resp.json()['ok'] == 1:
            logger.info(u'向群聊[%d]发送消息成功' % groupId)
            return None
        else:
            logger.warning(u'向群聊发送消息失败:%s' % resp.json()['msg'])
            return None

    def send_mess_to_one(self, userId, content):
        headers = {
            'Referer': 'https://m.weibo.cn/',
            'Upgrade-Insecure-Requests': '1'
        }
        referUrl = 'https://m.weibo.cn/msg/chat?uid=%s' % userId
        resp = HttpClient.get(referUrl, headers=headers)
        st = re.findall(r',"st":"(.*?)"', resp.text)[0]

        url = 'https://m.weibo.cn/msgDeal/sendMsg'
        data = {
            'fileId': None,
            'uid': userId,
            'content': content,
            'st': st,
        }

        headers = {
            'Referer': referUrl,
            'Origin': 'https://m.weibo.cn/'
        }
        resp = HttpClient.post(url, data, headers)
        if resp.status_code == 200 and resp.json()['ok'] == 1:
            logger.info(u'发送私信成功')
            return None
        else:
            logger.warning(u'向群聊发送消息失败:%s' % resp.json()['msg'])
            return None
